<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12">
        <h1 class="text-h4 font-weight-bold">个人资料</h1>
        <p class="text-subtitle-1 text-medium-emphasis">
          管理您的个人信息和账户设置
        </p>
      </v-col>
    </v-row>

    <v-row>
      <!-- 个人信息卡片 -->
      <v-col cols="12" md="4">
        <v-card class="mb-6">
          <v-card-text class="text-center pa-6">
            <v-avatar size="120" class="mb-4">
              <v-img :src="avatarUrl" :alt="user.name"></v-img>
            </v-avatar>
            
            <h2 class="text-h5 mb-2">{{ user.name }}</h2>
            <v-chip :color="roleColor" variant="elevated" class="mb-2">
              {{ roleText }}
            </v-chip>
            
            <div class="text-body-2 text-medium-emphasis">
              <div class="mb-1">
                <v-icon size="16" class="me-2">mdi-account</v-icon>
                {{ user.username }}
              </div>
              <div v-if="user.phone" class="mb-1">
                <v-icon size="16" class="me-2">mdi-phone</v-icon>
                {{ user.phone }}
              </div>
              <div v-if="user.email" class="mb-1">
                <v-icon size="16" class="me-2">mdi-email</v-icon>
                {{ user.email }}
              </div>
            </div>
          </v-card-text>
        </v-card>

       
      </v-col>

      <!-- 账户设置 -->
      <v-col cols="12" md="8">
        <v-card class="mb-6">
          <v-card-title>
            <v-icon class="me-2">mdi-account-edit</v-icon>
            基本信息
          </v-card-title>
          <v-card-text>
            <v-form ref="profileForm" @submit.prevent="updateProfile">
              <v-row>
                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="profileForm.name"
                    label="姓名"
                    variant="outlined"
                    density="comfortable"
                    :rules="nameRules"
                    required
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="profileForm.phone"
                    label="手机号"
                    variant="outlined"
                    density="comfortable"
                    :rules="phoneRules"
                  ></v-text-field>
                </v-col>
              </v-row>
              
              <v-btn
                type="submit"
                color="primary"
                :loading="profileLoading"
                class="mt-4"
              >
                更新信息
              </v-btn>
            </v-form>
          </v-card-text>
        </v-card>

        <!-- 修改密码 -->
        <v-card>
          <v-card-title>
            <v-icon class="me-2">mdi-lock-reset</v-icon>
            修改密码
          </v-card-title>
          <v-card-text>
            <v-form ref="passwordFormRef" @submit.prevent="changePassword">
              <v-text-field
                v-model="passwordForm.currentPassword"
                label="当前密码"
                :type="showCurrentPassword ? 'text' : 'password'"
                :append-inner-icon="showCurrentPassword ? 'mdi-eye' : 'mdi-eye-off'"
                @click:append-inner="showCurrentPassword = !showCurrentPassword"
                variant="outlined"
                density="comfortable"
                :rules="currentPasswordRules"
                required
              ></v-text-field>
              
              <v-text-field
                v-model="passwordForm.newPassword"
                label="新密码"
                :type="showNewPassword ? 'text' : 'password'"
                :append-inner-icon="showNewPassword ? 'mdi-eye' : 'mdi-eye-off'"
                @click:append-inner="showNewPassword = !showNewPassword"
                variant="outlined"
                density="comfortable"
                :rules="newPasswordRules"
                required
              ></v-text-field>
              
              <v-text-field
                v-model="passwordForm.confirmPassword"
                label="确认新密码"
                :type="showConfirmPassword ? 'text' : 'password'"
                :append-inner-icon="showConfirmPassword ? 'mdi-eye' : 'mdi-eye-off'"
                @click:append-inner="showConfirmPassword = !showConfirmPassword"
                variant="outlined"
                density="comfortable"
                :rules="confirmPasswordRules"
                required
              ></v-text-field>
              
              <v-btn
                type="submit"
                color="primary"
                :loading="passwordLoading"
                class="mt-4"
              >
                修改密码
              </v-btn>
            </v-form>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'

const authStore = useAuthStore()

// 响应式数据
const profileForm = ref({
  name: '',
  phone: '',
  email: ''
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const profileLoading = ref(false)
const passwordLoading = ref(false)
const showCurrentPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 计算属性
const user = computed(() => authStore.user || {})

const avatarUrl = computed(() => {
  return `https://api.dicebear.com/7.x/initials/svg?seed=${user.value.name}`
})

const roleText = computed(() => {
  const roleMap = {
    admin: '管理员',
    teacher: '教师',
    driver: '司机',
    after_school_teacher: '课后老师'
  }
  return roleMap[user.value.role] || user.value.role
})

const roleColor = computed(() => {
  const colorMap = {
    admin: 'red',
    teacher: 'blue',
    driver: 'green',
    after_school_teacher: 'orange'
  }
  return colorMap[user.value.role] || 'grey'
})

const roleIcon = computed(() => {
  const iconMap = {
    admin: 'mdi-shield-crown',
    teacher: 'mdi-school',
    driver: 'mdi-bus-school',
    after_school_teacher: 'mdi-book-open-variant'
  }
  return iconMap[user.value.role] || 'mdi-account'
})

const roleInfoTitle = computed(() => {
  const titleMap = {
    admin: '管理权限',
    teacher: '负责班级',
    driver: '校车信息',
    after_school_teacher: '课后班级'
  }
  return titleMap[user.value.role] || '角色信息'
})

const roleSpecificInfo = computed(() => {
  return (user.value.role === 'teacher' && user.value.classes) ||
         (user.value.role === 'driver' && user.value.driverInfo)
})

// 验证规则
const nameRules = [
  v => !!v || '姓名不能为空',
  v => v.length >= 2 || '姓名至少2个字符'
]

const phoneRules = [
  v => !v || /^1[3-9]\d{9}$/.test(v) || '请输入正确的手机号'
]

const emailRules = [
  v => !v || /.+@.+\..+/.test(v) || '请输入正确的邮箱地址'
]

const currentPasswordRules = [
  v => !!v || '请输入当前密码'
]

const newPasswordRules = [
  v => !!v || '请输入新密码',
  v => v.length >= 6 || '密码至少6位'
]

const confirmPasswordRules = [
  v => !!v || '请确认新密码',
  v => v === passwordForm.value.newPassword || '两次输入的密码不一致'
]

// 方法
const loadProfile = async () => {
  try {
    const response = await api.get('/auth/profile')
    const userData = response.data.data
    
    // 更新用户信息
    authStore.user = userData
    
    // 填充表单
    profileForm.value = {
      name: userData.name || '',
      phone: userData.phone || '',
      email: userData.email || ''
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    window.showNotification?.('加载用户信息失败', 'error')
  }
}

const updateProfile = async () => {
  const { valid } = await profileFormRef.value.validate()
  if (!valid) return
  
  profileLoading.value = true
  try {
    await api.put(`/users/${user.value.id}`, profileForm.value)
    
    // 更新本地用户信息
    authStore.user = {
      ...authStore.user,
      ...profileForm.value
    }
    localStorage.setItem('user', JSON.stringify(authStore.user))
    
    window.showNotification?.('个人信息更新成功', 'success')
    
  } catch (error) {
    console.error('更新个人信息失败:', error)
    window.showNotification?.('更新个人信息失败', 'error')
  } finally {
    profileLoading.value = false
  }
}

const changePassword = async () => {
  const { valid } = await passwordFormRef.value.validate()
  if (!valid) return
  
  passwordLoading.value = true
  try {
    const result = await authStore.changePassword({
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    if (result.success) {
      // 清空表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      
      window.showNotification?.('密码修改成功', 'success')
    } else {
      window.showNotification?.(result.message, 'error')
    }
    
  } catch (error) {
    console.error('修改密码失败:', error)
    window.showNotification?.('修改密码失败', 'error')
  } finally {
    passwordLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.v-card {
  transition: all 0.3s ease;
}

.v-card:hover {
  transform: translateY(-2px);
}

.v-avatar {
  border: 4px solid rgba(var(--v-theme-primary), 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .v-card-text {
    padding: 16px !important;
  }
}
</style>
